package component

import androidx.compose.foundation.BorderStroke
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.lt.load_the_image.rememberImagePainter
import constants.blueTeam
import constants.blueTeamColor
import constants.redTeam
import constants.redTeamColor
import kotlinx.serialization.Serializable
import kotlinx.serialization.json.Json
import serializer.BigDecimalSerializer
import java.math.BigDecimal

/**
 * @description 赛后结算
 * @author      wwg
 * @date        2024/5/15 23:02
 */

@Serializable
data class PlayerPostMatchSettlementDTO(
    val openId: String,
    val teamId: Long,
    val uname: String,
    val avatarUrl: String,
    val teamColor: String,
    @Serializable(BigDecimalSerializer::class)
    val dispatchPoint: BigDecimal,
    @Serializable(BigDecimalSerializer::class)
    val hangUpPenalty: BigDecimal,
    @Serializable(BigDecimalSerializer::class)
    val winningAddition: BigDecimal,
    @Serializable(BigDecimalSerializer::class)
    val winningStreakAddition: BigDecimal,
    @Serializable(BigDecimalSerializer::class)
    val contributionScore: BigDecimal,
    @Serializable(BigDecimalSerializer::class)
    val totalScore: BigDecimal,
)

@Serializable
data class PostMatchSettlementDTO(
    val display:Boolean = false,
    val winningTeamName: String = "",
    val playerMatchSettlementList: List<PlayerPostMatchSettlementDTO> = ArrayList()
)

var postMatchSettlementDTO = mutableStateOf(PostMatchSettlementDTO())

@Composable
fun SettlementList() {
    Box(
        modifier = Modifier
            .fillMaxSize(),
        contentAlignment = Alignment.Center
    ) {
        val playerMatchSettlementList by remember { mutableStateOf(postMatchSettlementDTO.value.playerMatchSettlementList) }
        val winningTeamNameState by remember { mutableStateOf(postMatchSettlementDTO.value.winningTeamName) }
        Image(
            painter = rememberImagePainter("image/rank_list_backend.png"),
            contentDescription = "",
            modifier = Modifier
                .fillMaxSize(),
            contentScale = ContentScale.Crop
        )
        Image(
            painter = rememberImagePainter("image/header_ornaments.png"),
            contentDescription = "",
            modifier = Modifier
                .width(600.dp)
                .padding(top = 80.dp)
                .align(Alignment.TopCenter),
//            contentScale = ContentScale.Crop
        )
        Text(
            text = "赛后结算",
            color = Color(0xFF341F1C),
            fontFamily = FontFamily.Monospace,
            fontWeight = FontWeight.Bold,
            fontSize = (30).sp,
            softWrap = false,
            overflow = TextOverflow.Visible,
            modifier = Modifier
                .padding(top = 100.dp)
                .align(Alignment.TopCenter)
        )
        Text(
            text = "获胜方：${winningTeamNameState}",
            color = Color(0xFF341F1C),
            fontFamily = FontFamily.Monospace,
            fontWeight = FontWeight.Bold,
            fontSize = (30).sp,
            softWrap = false,
            overflow = TextOverflow.Visible,
            modifier = Modifier
                .padding(top = 160.dp)
                .align(Alignment.TopCenter)
        )
        Row(
            modifier = Modifier
                .padding(top = 200.dp)
                .align(Alignment.TopCenter),
            horizontalArrangement = Arrangement.Center
        ) {
            val titleList = listOf("获胜积分", "连胜加成", "贡献积分", "挂机惩罚", "总积分")
            SettlementTable(playerMatchSettlementList, titleList)
            Spacer(modifier = Modifier.width(32.dp))
//            SingleColumnTable(currentRoundScoreList, "本局出兵积分榜")
//            Spacer(modifier = Modifier.width(32.dp))
//            SingleColumnTable(contributionValueList, "贡献总榜")
        }
//        Text(
//            text = "注：出兵积分总榜和贡献总榜数据记录起始日期为2024年4月14日",
//            color = Color(0xFF341F1C),
//            fontFamily = FontFamily.Monospace,
//            fontWeight = FontWeight.Bold,
//            fontSize = (20).sp,
//            softWrap = false,
//            overflow = TextOverflow.Visible,
//            modifier = Modifier
//                .padding(end = 200.dp, bottom = 40.dp)
//                .align(alignment = Alignment.BottomEnd)
//
//        )

    }
}

@Composable
fun PostMatchSettlementScreen() {
    val postMatchSettlementDTOState by remember { mutableStateOf(postMatchSettlementDTO) }
    Box(
        modifier = Modifier
            .fillMaxSize()
    ) {
        if (postMatchSettlementDTOState.value.display) {
            SettlementList()
        }
    }
}

@Composable
private fun SettlementTable(rows: List<PlayerPostMatchSettlementDTO>, title: List<String>) {
    Box(
        modifier = Modifier
            .width(1500.dp)
            .border(BorderStroke(2.dp, Color(0xFF341F1C)), shape = RoundedCornerShape(3.dp))
    ) {
        Column(
            modifier = Modifier.align(Alignment.Center)
        ) {
            TableTitle(title)
            rows.forEachIndexed { index, row ->
                TableRowItem(row.uname, row.avatarUrl, row.teamColor, row.winningAddition, row.winningStreakAddition, row.contributionScore, row.hangUpPenalty, row.totalScore, isEven = index % 2 == 0, index)
            }
        }
    }
}


@Composable
private fun TableTitle(title: List<String>) {
    Row(
        modifier = Modifier
            .fillMaxWidth()
            .background(Color(0xFFB4967B))
            .padding(8.dp)
        ,
        horizontalArrangement = Arrangement.SpaceBetween
    ) {
        val spacerWidth = 5
        Row(
            modifier = Modifier.width(200.dp),
//                    .align(Alignment.TopStart)
//                    .wrapContentWidth(),
            horizontalArrangement = Arrangement.Center
            //                .widthIn(min = textWidth.dp)
            //                .offset(x = offsetTransition.value.x.dp)
        ) {

            Text(
                text = "玩家昵称",
                color = Color(0xFF341F1C),
                fontFamily = FontFamily.Monospace,
                fontWeight = FontWeight.ExtraBold,
                fontSize = (19).sp,
                softWrap = false,
                overflow = TextOverflow.Visible,
                modifier = Modifier
                    .background(Color.Transparent)
            )
        }
        title.forEachIndexed { index, item ->
            Row(
                modifier = Modifier.width(120.dp),
                horizontalArrangement = Arrangement.Center
            ) {
                Text(
                    text = item,
                    color = Color(0xFF341F1C),
                    fontFamily = FontFamily.Monospace,
                    fontWeight = FontWeight.ExtraBold,
                    fontSize = (19).sp,
                    softWrap = false,
                    overflow = TextOverflow.Visible,
                    modifier = Modifier
                        .background(Color.Transparent)
                )
            }
        }
    }
}

@Composable
private fun TableRowItem(
    uname: String,
    avatarUrl: String,
    teamColor: String,
    winningAddition: BigDecimal,
    winningStreakAddition: BigDecimal,
    contributionScore: BigDecimal,
    hangUpPenalty: BigDecimal,
    totalScore: BigDecimal,
    isEven: Boolean,
    index: Int
) {
    val spacerWidth = 5

    Box(
        modifier = Modifier
            .fillMaxWidth()
            .background(if (isEven) Color(0xFFD5B393) else Color(0xFFBA9A7D))
            .padding(vertical = 4.dp),
        contentAlignment = Alignment.CenterStart
    ) {
        Row(
            modifier = Modifier
                .fillMaxWidth(),
            horizontalArrangement = Arrangement.SpaceBetween
        ) {
            Row(
                modifier = Modifier.width(200.dp),
//                    .align(Alignment.TopStart)
//                    .wrapContentWidth(),
                horizontalArrangement = Arrangement.Center
                //                .widthIn(min = textWidth.dp)
                //                .offset(x = offsetTransition.value.x.dp)
            ) {
                // 圆形头像框
                Box(
                    modifier = Modifier
                        .size(27.dp)
                        .padding(start = 8.dp)
                        .background(Color.Transparent, shape = CircleShape),
                    contentAlignment = Alignment.Center
                ) {
                    Image(
                        painter = rememberImagePainter(avatarUrl),
                        contentDescription = "",
                        modifier = Modifier
                            .clip(CircleShape),
                    )
                }

                Spacer(modifier = Modifier.width(spacerWidth.dp))

                Text(
                    text = uname,
                    //                color = Color(0xFF341F1C),
                    color = when (teamColor) {
                        redTeam -> redTeamColor
                        blueTeam -> blueTeamColor
                        else -> Color(0xFF341F1C)
                    },
                    fontWeight = FontWeight.ExtraBold,
                    fontFamily = FontFamily.Monospace,
                    fontSize = (17).sp,
                    softWrap = false,
                    overflow = TextOverflow.Ellipsis,
//                    modifier = Modifier.width(30.dp)
                )
            }
            Row(
                modifier = Modifier.width(120.dp),
                horizontalArrangement = Arrangement.Center
            ) {
                TableText(
                    winningAddition.setScale(0).toString(),
                    teamColor
                )
            }


            Row(
                modifier = Modifier.width(120.dp),
                horizontalArrangement = Arrangement.Center
            ) {
                TableText(
                    winningStreakAddition.setScale(0).toString(),
                    teamColor
                )
            }
            Row(
                modifier = Modifier.width(120.dp),
                horizontalArrangement = Arrangement.Center
            ) {
                TableText(
                    contributionScore.setScale(0).toString(),
                    teamColor
                )
            }
            Row(
                modifier = Modifier.width(120.dp),
                horizontalArrangement = Arrangement.Center
            ) {
                TableText(
                    hangUpPenalty.setScale(0).toString(),
                    teamColor
                )
            }
            Row(
                modifier = Modifier.width(120.dp),
                horizontalArrangement = Arrangement.Center
            ) {
                TableText(
                    totalScore.setScale(0).toString(),
                    teamColor
                )
            }
        }
    }
}

@Composable
fun TableText(
    text: String,
    teamColor: String
) {
    Text(
        text = text,
        color = when (teamColor) {
            redTeam -> redTeamColor
            blueTeam -> blueTeamColor
            else -> Color(0xFF341F1C)
        },
        fontFamily = FontFamily.Monospace,
        fontWeight = FontWeight.ExtraBold,
        fontSize = (17).sp,
        softWrap = false,
        overflow = TextOverflow.Visible,
        modifier = Modifier.padding(end = 8.dp)
    )
}

fun handlePostMatchSettlement(data: String) {
    postMatchSettlementDTO.value = Json.decodeFromString<PostMatchSettlementDTO>(data)
}

fun handlePostMatchSettlement() {
    val data = "{\"display\":true,\"winningTeamName\":\"蒙古\",\"playerMatchSettlementList\":[{\"openId\":\"openId_cc56386565dd\",\"teamId\":0,\"avatarUrl\":\"http://oss.jankinwu.com/img/%E5%BA%86%E7%A5%9D.png\",\"uname\":\"六等星的夜\",\"teamColor\":\"BLUE\",\"dispatchPoint\":0.00,\"hangUpPenalty\":-1.00,\"winningAddition\":1.00,\"winningStreakAddition\":2.00,\"contributionScore\":3.00,\"totalScore\":5.00}]}"
    postMatchSettlementDTO.value = Json.decodeFromString<PostMatchSettlementDTO>(data)
}